<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Room extends Model
{
    use HasFactory, LogsActivity;

    protected $fillable = [
        'room_id',
        'title',
        'description',
        'type',
        'creator_id',
        'menu_source',
        'menu_id',
        'settings',
        'expires_at',
        'status',
        'max_participants',
        'current_round',
        'total_orders',
        'last_activity_at',
    ];

    protected $casts = [
        'settings' => 'array',
        'expires_at' => 'datetime',
        'last_activity_at' => 'datetime',
    ];

    /**
     * 准备日期用于数组/JSON序列化
     */
    protected function serializeDate(\DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 房间创建者
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'creator_id');
    }

    /**
     * 房间成员
     */
    public function members(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'room_members')
                    ->withPivot(['role', 'joined_at', 'last_active_at', 'is_active', 'settings'])
                    ->withTimestamps();
    }

    /**
     * 房间订单
     */
    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }


    /**
     * 房间菜单
     */
    public function menu(): BelongsTo
    {
        return $this->belongsTo(Menu::class);
    }

    /**
     * 生成房间ID
     */
    public static function generateRoomId(): string
    {
        return 'room_' . time() . '_' . rand(1000, 9999);
    }

    /**
     * 检查房间是否过期
     */
    public function isExpired(): bool
    {
        if ($this->type === 'permanent') {
            return false;
        }

        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * 检查用户是否是房间成员
     */
    public function hasMember(int $userId): bool
    {
        return $this->members()->where('user_id', $userId)->exists();
    }

    /**
     * 检查用户是否是房间创建者
     */
    public function isCreator(int $userId): bool
    {
        return $this->creator_id === $userId;
    }

    /**
     * 获取用户角色
     */
    public function getUserRole(int $userId): ?string
    {
        $member = $this->members()->where('user_id', $userId)->first();
        return $member ? $member->pivot->role : null;
    }

    /**
     * 房间菜品（通过菜单关联）
     */
    public function dishes()
    {
        if (!$this->menu) {
            return collect();
        }
        return $this->menu->dishes();
    }

    /**
     * 获取房间菜单菜品
     */
    public function getRoomMenu(): \Illuminate\Support\Collection
    {
        if (!$this->menu) {
            return collect();
        }

        return $this->menu->dishes()
            ->with(['category', 'creator', 'sourceDish'])
            ->available()
            ->ordered()
            ->get();
    }

    /**
     * 活动日志配置
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['title', 'description', 'status', 'type', 'settings'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}